package com.jinsp.networklibrary;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;

import com.jinsp.networklibrary.command.CommandManager;
import com.jinsp.networklibrary.constant.TCPConnectConstant;
import com.jinsp.networklibrary.util.NetworkUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

//todo 同一进程服务
public class TCPConnectService extends Service {

    public static final String CONNECT_CONFIG = "connect_config";
    private static final String TAG = "TCPConnectService";
    private ConnectThread connectThread;
    private TCPConnectConfig tcpConnectConfig;

    public TCPConnectService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new ConnectServerImpl();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        tcpConnectConfig = intent.getParcelableExtra(CONNECT_CONFIG);
        Log.d(TCPConnectService.TAG, "客户端连接服务端参数：" + tcpConnectConfig);
        //销毁重建后保留原有赋值intent
        return START_REDELIVER_INTENT;
    }

    private class ConnectServerImpl extends IConnectServer.Stub {

        @Override
        public void connectServer(IConnectCallback connectCallback) throws RemoteException {
            if (NetworkUtils.isNetworkConnected(getApplicationContext())) {
                if (isConnected()) {
                    if (connectCallback != null) {
                        connectCallback.connectSuccess();
                    }
                    return;
                }
                if (tcpConnectConfig == null) {
                    if (connectCallback != null) {
                        connectCallback.connectFailed(TCPConnectConstant.TCP_CONNECT_ILLEGAL_IP);
                    }
                    return;
                }
                String serviceIp = tcpConnectConfig.getServiceIP();
                if (!TextUtils.isEmpty(serviceIp)) {
                    if (!NetworkUtils.isIPLegal(serviceIp)) {
                        if (connectCallback != null) {
                            connectCallback.connectFailed(TCPConnectConstant.TCP_CONNECT_ILLEGAL_IP);
                        }
                        return;
                    }
                    //开启连接线程
                    connectThread = new ConnectThread(tcpConnectConfig, connectCallback);
                    connectThread.start();
                }
            } else {
                if (connectCallback != null) {
                    connectCallback.connectFailed(TCPConnectConstant.NET_WORK_DISCONNECT);
                }
            }
        }

        @Override
        public boolean isConnected() throws RemoteException {
            return TCPSessionManager.getInstance().isConnected();
        }

        @Override
        public void disconnect() throws RemoteException {
            if (isConnected()) {
                connectThread.disconnect();
                connectThread = null;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CommandManager.getInstance().release();
        //关闭连接
        if (connectThread != null) {
            connectThread.disconnect();
            connectThread = null;
        }
    }

    private static class ConnectThread extends Thread {

        private final TCPConnectConfig tcpConnectConfig;
        private TCPConnectManager connectManager;
        private volatile boolean isStop;
        private final IConnectCallback mConnectCallback;

        public ConnectThread(TCPConnectConfig tcpConnectConfig, IConnectCallback connectCallback) {
            this.tcpConnectConfig = tcpConnectConfig;
            this.mConnectCallback = connectCallback;
        }

        @Override
        public void run() {
            super.run();
            connectManager = new TCPConnectManager(tcpConnectConfig);
            //尝试5次连接
            for (int i = 0; i < 3; i++) {
                if (!isStop) {
                    Log.d(TAG, "客户端开始第" + (i + 1) + "次连接");
                    boolean isTcpConnected = connectManager.connect();
                    if (isTcpConnected) {
                        Log.d(TAG, "客户端连接成功");
                        if (mConnectCallback != null) {
                            try {
                                mConnectCallback.connectSuccess();
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            }
                        }
                        return;
                    }
                    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
                }
            }
            if (!isStop) {
                //连接失败
                Log.d(TAG, "客户端连接失败");
                if (mConnectCallback != null) {
                    try {
                        mConnectCallback.connectFailed(TCPConnectConstant.TCP_CONNECT_TIME_OUT);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public void disconnect() {
            if (connectManager != null) {
                Log.d(TAG, "客户端关闭连接");
                isStop = true;
                connectManager.disconnect();
                connectManager = null;
            }
        }
    }
}